package handling;

import client.MapleClient;
import configs.ServerConfig;
import handling.cashshop.CashShopServer;
import handling.channel.ChannelServer;
import handling.login.LoginServer;
import handling.opcode.CashShopOpcode;
import handling.opcode.RecvPacketOpcode;
import handling.opcode.SendPacketOpcode;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import tools.Authorization;
import tools.MapleAESOFB;
import tools.Pair;
import tools.Randomizer;
import tools.data.input.ByteArrayByteStream;
import tools.data.input.GenericSeekableLittleEndianAccessor;
import tools.data.input.SeekableLittleEndianAccessor;
import tools.packet.LoginPacket;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class MapleServerHandler extends ChannelInboundHandlerAdapter {

    public static final List<String> BlockIPList = new ArrayList<>();
    public static final Logger AllPacketLog = LogManager.getLogger("AllPackets");
    public static final Logger BuffPacketLog = LogManager.getLogger("BuffPackets");
    public static final Logger AttackPakcetLog = LogManager.getLogger("AttackPackets");
    public static final boolean preventIpAttack = true;
    private static final Logger log = LogManager.getLogger(MapleServerHandler.class.getName());
    private static boolean show = false;
    private final Map<String, Pair<Long, Byte>> tracker = new ConcurrentHashMap<>();
    private ServerType type = null;
    private final HandlePacket handlePacket;
    private final ServerHandlerImp serverHandlerImp;

    public MapleServerHandler(ServerHandlerImp serverHandlerImp, ServerType type) {
        this.serverHandlerImp = serverHandlerImp;
        this.type = type;
        handlePacket = new HandlePacket();
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        // 开始检测IP
        String address = ctx.channel().remoteAddress().toString().split(":")[0];
        if (BlockIPList.contains(address)) { //是否在禁止的IP列表
            ctx.channel().close();
            return;
        }
        if (!address.equals("/127.0.0.1")) { // 过滤本地IP  && (type == ServerType.登录服务器 || type == ServerType.频道服务器)
            Pair<Long, Byte> track = tracker.get(address);
            byte count;
            if (track == null) {
                count = 1;
            } else {
                count = track.right;
                long difference = System.currentTimeMillis() - track.left;
                if (difference < 2000) { //同一个IP地址连接时间检测 当前为2秒
                    count++;
                } else if (difference > 20000) { //清除连接次数的时间 当前为20秒
                    count = 1;
                }
                if (preventIpAttack && count > 5) { // 单个IP的连接上限 达到多少次就禁止连接
                    BlockIPList.add(address);
                    tracker.remove(address); // Cleanup
                    ctx.channel().close();
                    return;
                }
            }
            tracker.put(address, new Pair<>(System.currentTimeMillis(), count));
            // 结束IP检测.
        }

        boolean inChannel = false;
        if (serverHandlerImp.getChannel() > -1) {
            if (ChannelServer.getInstance(serverHandlerImp.getChannel()).isShutdown()) { //如果频道是关闭的就断开连接
                ctx.channel().close();
                return;
            }
        } else if (type == ServerType.商城服务器) {
            inChannel = true;
            if (CashShopServer.getInstance().isShutdown()) {
                ctx.channel().close();
                return;
            }
        } else if (type == ServerType.登录服务器) {
            if (LoginServer.getInstance().isShutdown()) {
                ctx.channel().close();
                return;
            }
        }

        byte ivRecv[] = {(byte) Randomizer.nextInt(255), (byte) Randomizer.nextInt(255), (byte) Randomizer.nextInt(255), (byte) Randomizer.nextInt(255)};
        byte ivSend[] = {(byte) Randomizer.nextInt(255), (byte) Randomizer.nextInt(255), (byte) Randomizer.nextInt(255), (byte) Randomizer.nextInt(255)};
//        ivRecv[3] = (byte) (Math.random() * 255);
//        ivSend[3] = (byte) (Math.random() * 255);
        MapleAESOFB sendCypher = new MapleAESOFB(ivSend, (short) (0xFFFF - ServerConfig.LOGIN_MAPLE_VERSION));
        MapleAESOFB recvCypher = new MapleAESOFB(ivRecv, ServerConfig.LOGIN_MAPLE_VERSION);
        MapleClient client = new MapleClient(sendCypher, recvCypher, ctx.channel());
        client.setChannel(serverHandlerImp.getChannel());
        client.setWorld(serverHandlerImp.getWorldID());

//            client.setInChannel(inChannel);
        if (inChannel) {
            ctx.channel().writeAndFlush(LoginPacket.getHello(ServerConfig.LOGIN_MAPLE_VERSION, ivSend, ivRecv));
        } else {
            ctx.channel().writeAndFlush(LoginPacket.getHello2(ServerConfig.LOGIN_MAPLE_VERSION, ivSend, ivRecv));
        }

        ctx.channel().attr(MapleClient.CLIENT_KEY).set(client);

        if (Authorization.NoCheckKey.isDevelop) {
            RecvPacketOpcode.reloadValues();
            SendPacketOpcode.reloadValues();
            CashShopOpcode.reloadValues();
        }

        if (ServerConfig.WORLD_SHOWCONNECT) {
            StringBuilder sb = new StringBuilder();
            if (serverHandlerImp.getChannel() > -1) {
                sb.append("[Channel Server] Channel ").append(serverHandlerImp.getChannel()).append(" : ");
            } else if (type == ServerType.商城服务器) {
                sb.append("[Cash Server] ");
            } else {
                sb.append("[Login Server] ");
            }
            sb.append("IoSession opened ").append(address);
            System.out.println(sb.toString());
        }

        client.setThreadID(serverHandlerImp.getThreadID());
        client.sendPing();
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        MapleClient client = ctx.channel().attr(MapleClient.CLIENT_KEY).get();
        if (client != null) {
            try {
                client.disconnect(true, ServerType.商城服务器.equals(type));
            } catch (Throwable t) {
                log.error("连接异常关闭", t);
            } finally {
                ctx.channel().attr(MapleClient.CLIENT_KEY).set(null);
            }
        }
        ctx.channel().close();
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        SeekableLittleEndianAccessor slea = new GenericSeekableLittleEndianAccessor(new ByteArrayByteStream((byte[]) msg));
        if (slea.available() < 2) {
            return;
        }
        MapleClient client = ctx.channel().attr(MapleClient.CLIENT_KEY).get();
        if (client == null || !client.isReceiving()) {
            return;
        }
        serverHandlerImp.getWorkerQueue().runThread(client.getThreadID(), () -> {
            RecvPacketEntry recvPacketEntry = new RecvPacketEntry(ctx, msg, client, type);
            if (recvPacketEntry.getRecv() != null) {
                if (recvPacketEntry.getRecv().NeedsChecking() && !client.isLoggedIn()) {
                    return;
                }
                try {
                    if (client.getPlayer() != null && client.isMonitored() && ServerConfig.DEBUG_MODE) {
                        try (FileWriter fw = new FileWriter(new File("日志/MonitorLogs/" + client.getPlayer().getName() + "_log.txt"), true)) {
                            fw.write(String.valueOf(recvPacketEntry.getRecv()) + " (" + Integer.toHexString(recvPacketEntry.getHead()) + ") Handled: \r\n" + slea.toString() + "\r\n");
                            fw.flush();
                        }
                    }
                    handlePacket.handlePacket(recvPacketEntry.getRecv(), recvPacketEntry.getSlea(), client, type);
                } catch (Exception e) {
                    log.error("封包: " + lookupRecv(recvPacketEntry.getHead()) + "\r\n" + slea.toString(true), e);
                }
            }
        });
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) {
//        MapleClient client = ctx.channel().attr(MapleClient.CLIENT_KEY).get();
//        if (client != null) {
//            client.sendPing();
//        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        if (!(cause instanceof IOException)) {
            MapleClient client = ctx.channel().attr(MapleClient.CLIENT_KEY).get();
            if (client != null && client.getPlayer() != null && client.getPlayer().getMap() != null) {
                client.getPlayer().saveToDB(false, false, true);
                log.error("发现异常错误 玩家名:" + client.getPlayer().getName() + " 地图:" + client.getPlayer().getMap().getMapName() + "(" + client.getPlayer().getMapId() + ")", cause);
            } else if (client != null) {
                log.error("发现异常错误 账号:" + client.getAccountName(), cause);
            }
        }
    }

    private String lookupRecv(short header) {
        for (RecvPacketOpcode recv : RecvPacketOpcode.values()) {
            if (recv.getValue() == header) {
                return recv.name();
            }
        }
        return "UNKNOWN";
    }
}
